package com.ecoolex.chinadutyfree.retailer.api.graphql;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ecoolex.framework.modularize.api.service.storage.*;
import com.ecoolex.chinadutyfree.retailer.entity.DeliveryManner;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsOrder;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsOrderCoupon;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsOrderDetail;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsOrderIdentity;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsOrderReceiver;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsOrderSender;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsOrderShippedRecord;
import com.ecoolex.chinadutyfree.retailer.enums.DirectMailGoodsOrderStatus;
import com.ecoolex.chinadutyfree.retailer.pojo.CompleteDirectMailGoodsOrderIdentityDTO;
import com.ecoolex.chinadutyfree.retailer.pojo.DirectMailGoodsOrderChannelDTO;
import com.ecoolex.chinadutyfree.retailer.pojo.PreDirectMailGoodsOrderDTO;
import com.ecoolex.chinadutyfree.retailer.pojo.PreSubmitDirectMailGoodsOrderDTO;
import com.ecoolex.chinadutyfree.retailer.pojo.SubmitDirectMailGoodsOrderDTO;
import com.ecoolex.chinadutyfree.retailer.ws.DeliveryService;
import com.ecoolex.chinadutyfree.retailer.ws.DirectMailGoodsOrderService;
import com.ecoolex.chinadutyfree.retailer.ws.PaymentOrderService;
import com.ecoolex.framework.common.annotation.Description;
import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.pojo.Sorting;
import com.ecoolex.framework.modularize.api.service.currency.CurrencyType;
import com.ecoolex.framework.modularize.api.service.currency.CurrencyTypeService;
import com.ecoolex.framework.modularize.api.service.region.Region;
import com.ecoolex.framework.modularize.api.service.region.RegionService;
import com.ecoolex.framework.web.api.graphql2.annotation.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;

import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.util.Assert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.modularize.api.auth.user.ConsumerMemberAuthority;
import com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module.Type;


@GraphQL2Module(type = Type.User, description = "直邮商品订单操作")
public class DirectMailGoodsOrderGraphql {

	@Reference
	private PaymentOrderService paymentOrderService;
	
	@Reference
	private DirectMailGoodsOrderService directMailGoodsOrderService;

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private CurrencyTypeService currencyTypeService;

    @Autowired
    private StorageService storageService;

    @Autowired
    private RegionService regionService;
    
    @TypeField(type = DirectMailGoodsOrder.class, field = "currencyType", description = "币种")
    public CurrencyType currencyType(@Source DirectMailGoodsOrder source) {
        return currencyTypeService.get(source.getCurrencyType());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "canDelete", description = "是否能删除")
    public Boolean canDelete(@Source DirectMailGoodsOrder source) {
        return DirectMailGoodsOrderStatus.canDelete(source.getStatus());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "canCancel", description = "是否能取消")
    public Boolean canCancel(@Source DirectMailGoodsOrder source) {
        return DirectMailGoodsOrderStatus.canCancel(source.getStatus());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "canPay", description = "是否能支付")
    public Boolean canPay(@Source DirectMailGoodsOrder source) {
        return DirectMailGoodsOrderStatus.canPay(source.getStatus());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "canRefund", description = "是否能退款")
    public Boolean canRefund(@Source DirectMailGoodsOrder source) {
        return DirectMailGoodsOrderStatus.canRefund(source.getStatus());
    }
    
    @TypeField(type = DirectMailGoodsOrder.class, field = "canReturnAndExchange", description = "是否能退换货")
    public Boolean canReturnAndExchange(@Source DirectMailGoodsOrder source) {
        return DirectMailGoodsOrderStatus.canReturnAndExchange(source.getStatus());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "canConfirmReceipt", description = "是否能确认收货")
    public Boolean canConfirmReceipt(@Source DirectMailGoodsOrder source) {
        return DirectMailGoodsOrderStatus.canConfirmReceipt(source.getStatus());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "sender", description = "寄件人")
    public DirectMailGoodsOrderSender sender(@Source DirectMailGoodsOrder source) {
        return directMailGoodsOrderService.getSenderByOrderId(source.getOrderId());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "receiver", description = "收件人")
    public DirectMailGoodsOrderReceiver receiver(@Source DirectMailGoodsOrder source) {
        return directMailGoodsOrderService.getReceiverByOrderId(source.getOrderId());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "deliveryManner", description = "配送方式")
    public DeliveryManner deliveryManner(@Source DirectMailGoodsOrder source) {
        return deliveryService.getDeliveryMannerById(source.getDeliveryMannerId());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "identity", description = "订单身份信息")
    public DirectMailGoodsOrderIdentity identity(@Source DirectMailGoodsOrder source) {
        return directMailGoodsOrderService.getIdentityByOrderId(source.getOrderId());
    }

    @TypeField(type = DirectMailGoodsOrderIdentity.class, field = "frontImage", description = "正面照片")
    public StorageInfo frontImage(@Source DirectMailGoodsOrderIdentity source) {
        return storageService.get(source.getFrontImage());
    }

    @TypeField(type = DirectMailGoodsOrderIdentity.class, field = "backImage", description = "背面")
    public StorageInfo backImage(@Source DirectMailGoodsOrderIdentity source) {
        return storageService.get(source.getBackImage());
    }

    @TypeField(type = DirectMailGoodsOrderReceiver.class, field = "region", description = "区域信息")
    public Region receiver(@Source DirectMailGoodsOrderReceiver source) {
        return regionService.get(source.getRegionId());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "detailList", description = "订单详情")
    public List<DirectMailGoodsOrderDetail> detailList(@Source DirectMailGoodsOrder source) {
        return directMailGoodsOrderService.queryOrderDetailByOrderId(source.getOrderId());
    }
    
    @TypeField(type = DirectMailGoodsOrder.class, field = "orderCouponList", description = "订单优惠券列表")
    public List<DirectMailGoodsOrderCoupon> orderCouponList(@Source DirectMailGoodsOrder source) {
        return directMailGoodsOrderService.queryOrderCouponByOrderId(source.getOrderId());
    }

    @TypeField(type = DirectMailGoodsOrder.class, field = "shippedRecordList", description = "发货记录列表")
    public List<DirectMailGoodsOrderShippedRecord> shippedRecordList(@Source DirectMailGoodsOrder source) {
        return directMailGoodsOrderService.queryShippedRecordByOrderId(source.getOrderId());
    }

    @TypeField(type = DirectMailGoodsOrderShippedRecord.class, field = "deliveryManner", description = "配送方式")
    public DeliveryManner deliveryManner(@Source DirectMailGoodsOrderShippedRecord source) {
        return deliveryService.getDeliveryMannerById(source.getDeliveryMannerId());
    }

    @TypeField(type = DirectMailGoodsOrderDetail.class, field = "image", description = "产品图片")
    public StorageInfo image(@Source DirectMailGoodsOrderDetail source) {
        return storageService.get(source.getImage());
    }

    @QueryField(field = "preSubmitDirectMailGoodsOrder",
            description = { "预提交直邮商品订单","计算费用" })
    public PreDirectMailGoodsOrderDTO preSubmitDirectMailGoodsOrder(@NonNull PreSubmitDirectMailGoodsOrderDTO submit,
                                                                    ConsumerMemberAuthority user) {
        user.assertLogin();
        submit.setUserId(user.userId());
        PreDirectMailGoodsOrderDTO preDirectMailGoodsOrderDTO = directMailGoodsOrderService.preSubmitOrder(submit);
        return preDirectMailGoodsOrderDTO;
    }

    @QueryField(field = "directMailGoodsOrderDeliveryMannerListByCartIds", description = { "直邮商品订单配送方式列表" })
    public List<DeliveryManner> directMailGoodsOrderDeliveryMannerList(@Description({
            "购物车清单" }) @NonNull List<Integer> cartIdList, ConsumerMemberAuthority user) {
        user.assertLogin();
        return deliveryService.queryDeliveryMannerByUserShoppingCartIds(user.userId(), cartIdList);
    }

    @MutationField(field = "submitDirectMailGoodsOrder", description = "提交直邮商品订单")
    public DirectMailGoodsOrder submitDirectMailGoodsOrder(@NonNull SubmitDirectMailGoodsOrderDTO submit, CompleteDirectMailGoodsOrderIdentityDTO identity, DirectMailGoodsOrderChannelDTO channel, ConsumerMemberAuthority user) {
        user.assertLogin();
        submit.setUserId(user.userId());
        return directMailGoodsOrderService.submitOrder(submit, identity, channel, user.userName());
    }

    @MutationField(field = "cancelDirectMailGoodsOrder", description = "取消直邮商品订单")
    public DirectMailGoodsOrder cancelDirectMailGoodsOrder(@NonNull Integer orderId, ConsumerMemberAuthority user) {
        user.assertLogin();
        DirectMailGoodsOrder order = directMailGoodsOrderService.getOrderByIdAndUserId(orderId, user.userId());
        Assert.isTrue(Check.notNull(order), ResultCode.VERIFY.build(1), "订单不存在");
        return directMailGoodsOrderService.cancel(order, user.userName());
    }

    @MutationField(field = "delDirectMailGoodsOrder", description = "删除直邮商品订单")
    public Boolean delDirectMailGoodsOrder(@NonNull Integer orderId, ConsumerMemberAuthority user) {
        user.assertLogin();
        DirectMailGoodsOrder order = directMailGoodsOrderService.getOrderByIdAndUserId(orderId, user.userId());
        Assert.isTrue(Check.notNull(order), ResultCode.VERIFY.build(1), "订单不存在");
        directMailGoodsOrderService.deleteOrder(order, user.userName());
        return true;
    }

    @MutationField(field = "uploadDirectMailGoodsOrderIdentityFrontImage", description = { "上传直邮商品身份证正面" })
    public StorageInfo uploadDirectMailGoodsOrderIdentityFrontImage(@NonNull Upload request, ConsumerMemberAuthority user) {
        user.assertLogin();

        UploadSource uploadSource = new UploadSource("DirectMailGoodsOrderIdentity", "FrontImage");

        UploadLimit uploadLimit = new UploadLimit();
        uploadLimit.setMaxSize(FileSize.MB.byteLength(20));
        uploadLimit.setAllowMimeType(MimeType.IMAGE.commons());

        return storageService.upload(request, uploadSource, uploadLimit);
    }

    @MutationField(field = "uploadDirectMailGoodsOrderIdentityBackImage", description = { "上传直邮商品身份证反面" })
    public StorageInfo uploadDirectMailGoodsOrderIdentityBackImage(@NonNull Upload request, ConsumerMemberAuthority user) {
        user.assertLogin();
        UploadSource uploadSource = new UploadSource("DirectMailGoodsOrderIdentity", "BackImage");

        UploadLimit uploadLimit = new UploadLimit();
        uploadLimit.setMaxSize(FileSize.MB.byteLength(20));
        uploadLimit.setAllowMimeType(MimeType.IMAGE.commons());

        return storageService.upload(request, uploadSource, uploadLimit);
    }

    @MutationField(field = "confirmDirectMailGoodsOrderReceipt", description = "确认直邮商品订单收货")
    public DirectMailGoodsOrder confirmDirectMailGoodsOrderReceipt(@NonNull Integer orderId, ConsumerMemberAuthority user) {
        user.assertLogin();
        DirectMailGoodsOrder order = directMailGoodsOrderService.getOrderByIdAndUserId(orderId, user.userId());
        Assert.isTrue(Check.notNull(order), ResultCode.VERIFY.build(1), "订单不存在");
        return directMailGoodsOrderService.confirmReceipt(order, user.userName());
    }

    @QueryField(field = "directMailGoodsOrder", description = "直邮商品订单")
    public DirectMailGoodsOrder get(@NonNull Integer orderId, ConsumerMemberAuthority user) {
        user.assertLogin();
        return directMailGoodsOrderService.getOrderByIdAndUserId(orderId, user.userId());
    }

    @QueryField(field = "directMailGoodsOrderByNo", description = "根据订单号查询直邮商品订单")
    public DirectMailGoodsOrder byOrderNo(@NonNull String orderNo, ConsumerMemberAuthority user) {
        user.assertLogin();
        return directMailGoodsOrderService.getOrderByNoAndUserId(orderNo, user.userId());
    }

    @QueryField(field = "directMailGoodsOrderList", description = "直邮商品订单列表")
    public Pagination<DirectMailGoodsOrder> query(List<String> status, @NonNull Sorting[] sorts, @NonNull Page page, ConsumerMemberAuthority user) {
        user.assertLogin();
        return directMailGoodsOrderService.queryUserData(user.userId(), status, sorts, page);
    }

    @QueryField(field = "directMailGoodsOrderWaitSendingTotalNumber", description = "直邮商品订单等待发货总数")
    public Long directMailGoodsOrderWaitSendingTotalNumber(ConsumerMemberAuthority user) {
        if (user.isLogin()) {
            return directMailGoodsOrderService.countTotalNumberByStatus(user.userId(), DirectMailGoodsOrderStatus.PAID);
        } else {
            return 0L;
        }
    }

    @QueryField(field = "directMailGoodsOrderUnpaidTotalNumber", description = "直邮商品订单待支付总数")
    public Long directMailGoodsOrderUnpaidTotalNumber(ConsumerMemberAuthority user) {
        if (user.isLogin()) {
            return directMailGoodsOrderService.countTotalNumberByStatus(user.userId(), DirectMailGoodsOrderStatus.UNPAID);
        } else {
            return 0L;
        }
    }
    
    @MutationField(field = "pay",description = "发起订单支付")
	public String pay(@NonNull Integer orderId,@Description({"支付方式：1-UnionPayWap;2-NihaoPay"}) Integer type, HttpServletRequest request, HttpServletResponse resp, ConsumerMemberAuthority user){
		user.assertLogin();
		DirectMailGoodsOrder order = directMailGoodsOrderService.getByOrderId(orderId);
		Assert.isTrue(Check.notNull(order),ResultCode.VERIFY.build(1), "商品订单不存在");
		resp.setContentType("text/html;chartset=utf-8");
		
		return paymentOrderService.pay(type,order.getOrderNo(),order.getCurrencyType(),
			order.getUserId(),order.getRealPrice(),order.getCreateTime(),request,resp, user.userName());
	}
    
}
